import { serverlogin, bindPhone as bindPhoneApi } from "@/api/login";
import { useStorage } from "@/hooks/useStorage";
import { useRouter } from "@/hooks/useRouter";

const { setItem, getItem } = useStorage();
const router = useRouter();

export const TOKEN_KEY = "SERVER_Token";
export const USERINFO_KEY = "SERVER_USERINFO";

export function getToken() {
  return getItem(TOKEN_KEY);
}
export function getStorageUserInfo() {
  return getItem(USERINFO_KEY);
}
export function uniLogin(): Promise<string> {
  return new Promise((reslove, reject) => {
    uni.login({
      success(res: any) {
        if (res.code) {
          reslove(res.code);
        } else {
          reject(res.errMsg);
        }
      },
    });
  });
}
export function checkSession() {
  return uni.checkSession();
}

// 获取用户信息
export function getUserInfo(): Promise<UniApp.GetUserInfoRes> {
  return new Promise((resolve, rejects) => {
    uni.getUserProfile({
      success(res) {
        resolve(res);
      },
      fail(err) {
        rejects(err);
      },
    });
  });
}
// 判断是否授权手机号
export function isAuth() {
  const userInfo = getStorageUserInfo();

  if (userInfo?.phone) return true;
  router.push({
    path: "/pages/register/index",
  });
  return false;
}
export function useLogin() {
  const login = async () => {
    try {
      const code: string = await uniLogin();
      const serviceData: any = await serverlogin(code);
      setItem(TOKEN_KEY, serviceData.token);
      setItem(USERINFO_KEY, serviceData.userInfo);

      router.redirect({
        path: "/pages/home/index",
      });
    } catch (error) {
      // 测试用
      router.redirect({
        path: "/pages/home/index",
      });
    }
  };
  const bindPhone = async (code: string) => {
    const serviceData: any = await bindPhoneApi(code);
    setItem(TOKEN_KEY, serviceData.token);
    setItem(USERINFO_KEY, serviceData.userInfo);
  };

  return { login, getToken, bindPhone };
}
